import {
  login,
  logout,
  getCurrUserInfo
} from "@/api/login";
import {
  getUserInfo,
  getStaffInfo,
  getMenuInfo
} from "@/api/common";
import utils from "@/utils/index";
import router from "@/router/index";
// import {
//     asyncRouterMap
// } from '@/router'

import {
  removeAuth,
  getMenu,
  setMenu
} from "@/utils/auth";
import {
  getTrees
} from "@/utils/index";

//将路由转换成可以完全遍历的树，并且拼接完全路由路径
export const convert_router_data = (data) => {
  data = JSON.parse(JSON.stringify(data));
  for (var i = 0; i < data.length; i++) {
    data[i].routerPath = data[i].routerPath || data[i].path;
    //为了不追加首页的路由，因为/home不是具体页面
    if (data[i].routerPath == "/Home") {
      data[i].routerPath = "/";
    }
    if (data[i].children != undefined) {
      var temp = data[i].children;
      // 删除孩子节点
      delete data[i].children;
      // 孩子节点加入数组末尾
      for (var j = 0; j < temp.length; j++) {
        //拼接完整路径
        let str = data[i].routerPath.startsWith("/") ? "" : "/";
        let str1 = temp[j].path.startsWith("/") ? "" : "/";
        let strPath = str + data[i].routerPath + str1 + temp[j].path;
        //将多余的斜杆变成一个
        temp[j].routerPath = strPath.replace("//", "/");
        data.push(temp[j]);
      }
    }
  }
  return data;
};
//整个树菜单，分成firstNav,secondNav
const finishMenuInfo = (authInfo = []) => {
  //将路由转变成可以遍历完全的数组，取路由里的path,添加到菜单里
  let routerList = convert_router_data(asyncRouterMap);

  authInfo.map((auth) => {
    let routerObj = routerList.find(
      (router) => router.meta && router.meta.code == auth.code
    );
    auth.path = routerObj ? routerObj.routerPath : "";
    auth.navTitle = auth.menuName;
  });
  let menuInfo = this.$utils.getTrees(
    authInfo,
    null, //后台第一个节点没有parentId,该值根据后台返回值变更
    "id",
    "parentId",
    "menuName"
  );
  let menuObj = {
    firstNav: [], //一级菜单
    secondNav: {}, //二级导航
    btnAuth: {}, //按钮权限
    authList: JSON.parse(JSON.stringify(authInfo)),
  };

  menuObj.firstNav = [...menuInfo];
  authInfo
    .filter((i) => i.funcList && i.funcList.length)
    .map((i) => {
      menuObj.btnAuth[i.code] = i.funcList;
    });
  menuInfo.map((i) => {
    if (i.children) {
      menuObj.secondNav[i.code] = i.children;
    }
  });
  return menuObj;
};
const appListChange = (appList = []) => {
  appList.map((i) => {
    i.name = i.appName;
    i.value = i.appMark;
  });
  return appList;
};

const user = {
  state: {
    menuPictures: [
      {
        code: "systemManagement",
        name: "系统管理",
        router: "/systemManagement",
        status: true,
        imgSrc: require("@/assets/img/workStation/xtgl.svg"),
      },
      {
        code: "standardManagement",
        name: "标准管理",
        router: "/standardManagement",
        status: true,
        imgSrc: require("@/assets/img/workStation/bzgl.svg"),
      },
      {
        code: "twoTicketManagement",
        name: "两票管理",
        router: "/twoTicketManagement",
        status: true,
        imgSrc: require("@/assets/img/workStation/lpgl.svg"),
      },
      {
        code: "equipmentLedger",
        name: "设备台账",
        router: "/equipmentLedger",
        status: true,
        imgSrc: require("@/assets/img/workStation/sbtz.svg"),
      },
      {
        code: "productionPlan",
        name: "生产计划",
        router: "/productionPlan",
        status: true,
        imgSrc: require("@/assets/img/workStation/scjh.svg"),
      },
      {
        code: "orderManagement",
        name: "工单管理",
        router: "/orderManagement",
        status: true,
        imgSrc: require("@/assets/img/workStation/gdgl.svg"),
      },
      {
        code: "operationManagement",
        name: "运行管理",
        router: "/operationManagement",
        status: true,
        imgSrc: require("@/assets/img/workStation/yxgl.svg"),
      },
      {
        code: "businessConfigurationManagement",
        name: "业务配置管理",
        router: "/businessConfigurationManagement",
        status: true,
        imgSrc: require("@/assets/img/workStation/ywpzgl.svg"),
      },
      {
        code: "upComingCenter",
        name: "待办中心",
        router: "/upComingCenter",
        status: true,
        imgSrc: require("@/assets/img/workStation/dbzx.svg"),
      },
      {
        code: "tjzx",
        name: "报表中心",
        router: "/tjzx",
        status: true,
        imgSrc: require("@/assets/img/workStation/bbzx.svg"),
      },
      {
        code: "intelligentInspection",
        name: "智能巡检",
        router: "/intelligentInspection",
        status: true,
        imgSrc: require("@/assets/img/workStation/znxj.svg"),
      },
      {
        code: "remoteSupport",
        name: "远程支持",
        link: `https://10.21.21.87?userId=`,
        isOutLink: true,
        status: true,
        imgSrc: require("@/assets/img/workStation/remoteSupport.png"),
      }
    ],
    userInfo: null, // 用户信息
    mineUserInfo: null,
    appListData: [], //应用权限
    // 权限信息
    allAuth: {}, //总权限信息 默认空 调整动态路由
    currentInfo: {}, //当前水司，组织，身份信息
    currentSecondNav: [], //当前二级菜单的权限
    currentButtonAuth: [], //当前页面按钮的权限
    avatarUrl: null,
  },

  mutations: {
    SET_STAFFINFO: (state, staffInfo) => {
      if (staffInfo) {
        if (staffInfo.agent) {
          state.mineUserInfo = staffInfo.agent;
        } else {
          state.mineUserInfo = staffInfo;
        }
        state.userInfo = staffInfo;
        localStorage.setItem("OUT_ORG", staffInfo.isOutOrg || 0);
      } else {
        state.userInfo = null;
      }
    },
    SET_AVATARURL: (state, url) => {
      state.avatarUrl = url;
    },
    SET_CURRENTINFO: (state, staffInfo) => {
      if (staffInfo) {
        let currentInfo = {};
        if(localStorage.getItem("currOrgName")) {
          currentInfo.currOrgName = localStorage.getItem("currOrgName")
        } else {
          currentInfo.currOrgName = staffInfo.orgName || ''
        }
        if (localStorage.getItem("currOrg")) {
          currentInfo.currOrg = localStorage.getItem("currOrg");
        } else {
          let defaultOrg = state.mineUserInfo.orgVoList.filter(
            (item) => item.defaultFlag == 1
          );
          currentInfo.currOrg =
            defaultOrg.length != 0
              ? defaultOrg[0].id
              : state.mineUserInfo.orgVoList[0].id;
          localStorage.setItem("currOrg", currentInfo.currOrg);
        }
        if (localStorage.getItem("currDs")) {
          currentInfo.currDs = localStorage.getItem("currDs");
        } else {
          currentInfo.currDs = staffInfo.defaultAppId
            ? staffInfo.defaultAppId
            : staffInfo.appSimpleBeanList[0].appMark;
          localStorage.setItem("currDs", currentInfo.currDs);
        }
        if (localStorage.getItem("currLeader")) {
          currentInfo.currLeader = localStorage.getItem("currLeader");
        } else {
          currentInfo.currLeader = staffInfo.account;
          localStorage.setItem("currLeader", currentInfo.currLeader);
        }
        if (localStorage.getItem("currLeaderOrg")) {
          currentInfo.currLeaderOrg = localStorage.getItem("currLeaderOrg");
        } else {
          if (staffInfo.agent) {
            let defaultOrg = staffInfo.orgVoList.filter(
              (item) => item.defaultFlag == 1
            );
            currentInfo.currLeaderOrg =
              defaultOrg.length != 0
                ? defaultOrg[0].id
                : staffInfo.orgVoList[0].id;
            localStorage.setItem("currLeaderOrg", currentInfo.currLeaderOrg);
          }
        }
        state.currentInfo = currentInfo;
      } else {
        state.currentInfo = {};
      }
    },
    SET_CURRDS: (state, currDs) => {
      localStorage.setItem("currDs", currDs);
      state.currentInfo.currDs = currDs;
    },
    SET_CURRORG: (state, currOrg) => {
      localStorage.setItem("currOrg", currOrg);
      state.currentInfo.currOrg = currOrg;
    },
    SET_CURRIDEN: (state, currIden) => {
      localStorage.setItem("currLeader", currIden);
      state.currentInfo.currLeader = currIden;
      delete state.currentInfo.currLeaderOrg;
    },
    SET_CURRLEADERORG: (state, currLeaderOrg) => {
      localStorage.setItem("currLeaderOrg", currLeaderOrg);
      state.currentInfo.currLeaderOrg = currLeaderOrg;
    },
    SET_APPLIST: (state, appListData) => {
      state.appListData = appListData.map((item) => {
        const obj = {
          label: item.appName,
          value: item.appMark,
          appId: item.appId,
          appCode: item.appCode,
        };
        return obj;
      });
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_ALLAUTH: (state, appMark) => {
      const authInfo = {
        appList: [],
        menuList: [],
        firstNav: {},
        secondNav: {},
        btnAuth: [],
      };
      let menuList = [];
      state.userInfo.userOwnJurisdictionBean.appMenuJurisdictionBeanList.forEach(
        (item) => {
          if (item.mark == appMark) {
            item.menuJurisdictionBeanList.forEach((list) => {
              if (list.isFunc == 0) {
                menuList.push(list);
              } else {
                authInfo.btnAuth.push(list);
              }
            });
          }
        }
      );
      authInfo.menuList = menuList;
      let result = utils.getTrees(menuList, 0, "menuId", "parent", "name");
      let menuRoutes = setMenu(result);
      try {
        let arrs = router.options.routes.concat(menuRoutes);
        router.options.routes = arrs;
        router.addRoutes(menuRoutes);
      } catch (error) {
        console.log(error);
      }
      result.forEach((item) => {
        if (item.isOpen && item.status) {
          state.menuPictures.forEach((list) => {
            if (list.code == item.menuCode) {
              authInfo.appList.push(list);
            }
          });
        }
        if (item.children) {
          authInfo.firstNav[`${item.menuCode}`] = item.children.map((child) => {
            if (child.children) {
              authInfo.secondNav[`${child.menuCode}`] = child.children.map(
                (i) => {
                  const obj = {
                    navTitle: i.name,
                    path: `/${item.menuCode}/${child.menuCode}/${i.menuCode}`,
                    code: i.menuCode,
                    isShow: i.isOpen && i.status,
                  };
                  if (i.children) {
                    obj.children = i.children.map((element) => {
                      const obj = {
                        navTitle: element.name,
                        path: `/${item.menuCode}/${child.menuCode}/${i.menuCode}/${element.menuCode}`,
                        code: element.menuCode,
                        isShow: element.isOpen && element.status,
                      };
                      return obj;
                    });
                  }
                  return obj;
                }
              );
            }
            const obj = {
              navTitle: child.name,
              path: `/${item.menuCode}/${child.menuCode}`,
              code: child.menuCode,
              isShow: child.isOpen && child.status,
            };
            return obj;
          });
        }
      });
      state.allAuth = authInfo;
    },
    /**设置当前页面的按钮权限 */
    SET_CURRENT_BTN_AUTH: (state, pageCode) => {
      let btnAuth = [];
      if (state.allAuth && state.allAuth.btnAuth) {
        state.allAuth.btnAuth.forEach((item) => {
          if (item.menuCode == pageCode) {
            btnAuth.push(item.funcCode);
          }
        });
      }
      state.currentButtonAuth = btnAuth;
    },
  },

  actions: {
    //获取用户信息
    GetUserInfo({ commit }, params) {
      return new Promise((resolve, reject) => {
        let param = {
          token: localStorage.getItem("GDH_WATER_TOKEN")
            ? localStorage.getItem("GDH_WATER_TOKEN")
            : process.env.VUE_APP_TOKEN,
        };
        getCurrUserInfo(param)
          .then((res) => {
            commit("SET_STAFFINFO", res.data);
            let photo;
            if (res.data.agent) {
              photo = res.data.agent.photo;
            } else {
              photo = res.data.photo;
            }
            if (photo) {
              utils.echoImg(photo).then((res) => {
                commit("SET_AVATARURL", res);
              });
            } else {
              commit("SET_AVATARURL", null);
            }
            let appList = res.data.userOwnJurisdictionBean.appSimpleBeanList;
            commit("SET_APPLIST", appList);
            commit("SET_CURRENTINFO", res.data);
            let currDs = res.data.defaultAppId
              ? res.data.defaultAppId
              : appList[0].appMark;
            let appMark = localStorage.getItem("currDs")
              ? localStorage.getItem("currDs")
              : currDs;
            commit("SET_ALLAUTH", appMark);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 登录
    Login({ commit }, userInfo) {
      0;
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        login(username, userInfo.password)
          .then((data) => {
            commit("SET_USERINFO", data.user);
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //通过账号查询用户的权限及基本信息
    getStaff({ commit }, account) {
      return new Promise((resolve, reject) => {
        getStaffInfo(account).then((res) => {
          let data = res.data;
          if (data) {
            commit("SET_STAFFINFO", data);
            let appList = appListChange(
              data.userOwnJurisdictionBean.appSimpleBeanList
            );
            commit("SET_APPLIST", appList);
          }
        });
        resolve();
      });
    },

    // 获取权限
    GetAuth({ commit }, { systemCode }) {
      return new Promise((resolve, reject) => {
        Promise.all([getMenuInfo(systemCode)])
          .then((resArr) => {
            let [menuRes] = resArr;
            let { data: menuData } = menuRes;
            let allAuth = finishMenuInfo(menuData);
            commit("SET_ALLAUTH", allAuth);
            resolve(menuData);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //设置当前页面的按钮权限
    setCurrentBtnAuth({ commit }, pageCode) {
      return new Promise((resolve, reject) => {
        commit("SET_CURRENT_BTN_AUTH", pageCode);
        resolve(true);
      });
    },
    //移除权限
    removeAllAuth({ commit }) {
      return new Promise((resolve, reject) => {
        commit("SET_ALLAUTH", null);
        resolve();
      });
    },
    //改变一级菜单时，修改state里的firstNav/SecondNav
    changeFirstNav({ commit }, { path }) {
      return new Promise((resolve, reject) => {
        let {
          allFirstNav: firstNav,
          allSecondNav: secondNav,
        } = this.getters.allAuth;
        let menuInfo = {
          firstNav,
          secondNav,
        };
        commit("SET_ALLAUTH", secondToFirstMenu(menuInfo, path));
        resolve();
      });
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        // logout().then(() => {
        /** flush 清空localStorage .rm('authKey') 按照key清除 */
        removeAuth();
        resolve();
        // }).catch(error => {
        // reject(error)
        // })
      });
    },
  },
};

export default user;